package edu.ccut.titan.core.impl.resources;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;

import org.apache.commons.io.FileUtils;
import org.osgi.framework.Bundle;

import edu.ccut.titan.component.TitanComponentException;

/**
 * Deploy and undo deploy web resource from a bundle
 * 
 * @author LeslieGu
 * 
 */
public class WebResourceResolver {

	/**
	 * deploy a directory in bundle to web root path
	 * 
	 * @param bundle
	 * @param directoryPath
	 * @param webRootBundlePath
	 * @throws TitanComponentException
	 */
	@SuppressWarnings("unchecked")
	public static void deploy(Bundle bundle, String directoryPath,
			String webRootBundlePath) throws TitanComponentException {

		createDirctory(webRootBundlePath);

		copyDirectory(bundle, directoryPath, webRootBundlePath);
	}

	public static void undeploy(String webRootBundlePath)throws TitanComponentException {
		if (webRootBundlePath != null) {
			File directory = new File(webRootBundlePath);
			try {
				FileUtils.deleteDirectory(directory);
			} catch (IOException e) {
				throw new TitanComponentException(e);
			}
		}

		// TODO:是否有更好的方案，现在没有删除容器的jsp缓存
	}

	@SuppressWarnings("unchecked")
	private static void copyDirectory(Bundle bundle, String directoryPath,
			String copyPath) throws TitanComponentException {

		createDirctory(copyPath + "/" + directoryPath);

		Enumeration<String> filePaths = bundle.getEntryPaths(directoryPath);

		if (filePaths == null) {
			return;
		}

		while (filePaths.hasMoreElements()) {
			String filePath = filePaths.nextElement();

			if (filePath.endsWith("/")) {
				copyDirectory(bundle, filePath, copyPath);
			} else {
				createFile(bundle, copyPath + "/" + filePath, filePath);
			}
		}
	}

	private static void createDirctory(String path)
			throws TitanComponentException {
		File directory = new File(path);

		if (directory.exists()) {
			try {
				FileUtils.deleteDirectory(directory);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (!directory.mkdirs()) {
			throw new TitanComponentException("create direcory failed in ["
					+ path + "]");
		}
	}

	private static void createFile(Bundle bundle, String copyFilePath,
			String filePath) throws TitanComponentException {
		try {
			File file = new File(copyFilePath);

			URL url = bundle.getEntry(filePath);

			FileUtils.copyURLToFile(url, file);
		} catch (IOException e) {
			throw new TitanComponentException("create file failed in ["
					+ copyFilePath + "]");
		}
	}
}
